﻿using System;
using System.Collections.Generic;
using System.Text;
using ChemicalEquilibrium;

namespace NeuralModule
{
    /// <summary>
    /// 轴突
    /// 分类:
    ///     简单轴突
    ///         功能:
    ///             由电压门控Na通道向后传递动作电位
    ///         平衡:
    ///             离子平衡
    /// </summary>
    public class Axon
    {
        public List<ThreadEventWait> TEWs = new List<ThreadEventWait>();

        public Reactants FormerIonK, FormerIonNa;

        public Reactants IonK, IonNa;

        public Reactants ChannelNa;

        public IonicEquilibrium IENa;

        public VoltageGated VGChannelNa;

        public ReactantTransform RTK, RTNa;

        public Axon(Reactants FormerIonK, Reactants FormerIonNa)
        {
            this.FormerIonK = FormerIonK;
            this.FormerIonNa = FormerIonNa;

            Initialize();
        }

        public void Initialize()
        {
            //离子
            this.IonK = new Reactants(100000, 100000);
            this.IonNa = new Reactants(100000, 100000);

            //离子通道
            this.ChannelNa = new Reactants(0, 1000);

            //离子平衡
            this.IENa = new IonicEquilibrium(this.ChannelNa.Active, this.IonNa.Active, this.IonNa.Inactive, 1f, 128, this.GetVoltage);

            //电压门控Na离子通道
            this.VGChannelNa = new VoltageGated(this.ChannelNa, -40, 40, -60, 40, 20, this.GetVoltage);

            //模块间离子平衡
            this.RTK = new ReactantTransform(this.FormerIonK, this.IonK);
            this.RTNa = new ReactantTransform(this.FormerIonNa, this.IonNa);

            this.TEWs.Add(new ThreadEventWait(100, this.VGChannelNa.Transport));
            this.TEWs.Add(new ThreadEventWait(100, new OperateCallback(this.IENa.Transport)));
            this.TEWs.Add(new ThreadEventWait(500, new OperateCallback(this.RTK.Transform)));
            this.TEWs.Add(new ThreadEventWait(500, new OperateCallback(this.RTNa.Transform)));
        }

        public void Start()
        {
            foreach (ThreadEventWait TEW in this.TEWs) TEW.Start();
        }

        public void Abort()
        {
            foreach (ThreadEventWait TEW in this.TEWs) TEW.Abort();
        }

        float Capacitance = 0.001f;
        public int GetVoltage()
        {
            int voltage = (int)((this.IonK.Active.Count + this.IonNa.Active.Count - this.IonK.Inactive.Count - this.IonK.Inactive.Count) * this.Capacitance);
            return voltage;
        }
    }
}
